package com.android.citynetworkpin.fragment.group;

import android.content.Context;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.citynetworkpin.R;
import com.android.citynetworkpin.fragment.BaseLazyFragment;
import com.android.citynetworkpin.model.group.ThematicAGoodsData;
import com.android.citynetworkpin.model.group.ThematicAGoodsDataCallback;
import com.android.citynetworkpin.utils.ConstantsUrl;
import com.android.citynetworkpin.utils.HttpUtils;
import com.android.citynetworkpin.utils.ObjectUtils;
import com.android.citynetworkpin.view.recycleview.CustomLoadMoreView;
import com.android.citynetworkpin.view.recycleview.CustomRecycleView;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * Created by Administrator on 2017/6/19.
 */

public class Fragment_ThematicAList extends BaseLazyFragment implements BaseQuickAdapter.RequestLoadMoreListener {
    @BindView(R.id.no_data)
    RelativeLayout noData;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.single_talist_fragment)
    FrameLayout single_talist_fragment;
    @BindView(R.id.twocascade_talist_fragment)
    FrameLayout twocascade_talist_fragment;
    @BindView(R.id.tab)
    TabLayout tabLayout;
    @BindView(R.id.pager)
    ViewPager viewPager;
    @BindView(R.id.ta_onecascade_listview)
    CustomRecycleView listview;
    private static final String ARG_PARAM1 = "param1";
    private String ta_id;
    private LayoutInflater inflater;
    private View view;
    private ImageView osthematic_head_banner_iv;
    private ImageView up_img;
    private FragmentActivity mcontext;
    private boolean networkConnected;
    private GroupFragmentPagerAdapter pagerAdapter;
    private Adapt adapter;
    private ArrayList<ThematicAGoodsData.DataBean.Cat_listDataBean> cat_list = new ArrayList<>();
    private ArrayList<ThematicAGoodsData.DataBean.ListDataBean> listdata = new ArrayList<>();
    private StaggeredGridLayoutManager mLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
    private int page = 1;
    private View frament_head;

    public static Fragment_ThematicAList newInstance(String need_id) {
        Fragment_ThematicAList fragment = new Fragment_ThematicAList();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, need_id);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            ta_id = getArguments().getString(ARG_PARAM1);
        }
    }

    @Override
    protected View initView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        this.inflater = inflater;
        view = inflater.inflate(R.layout.fragment_thematicactivity_list, container, false);
        mcontext = getActivity();
        ButterKnife.bind(this, view);
        initUI();
        return view;
    }

    @Override
    protected void initPrepare() {

    }

    @Override
    protected void onInvisible() {

    }

    @Override
    protected void initData() {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            GetTAGoods();
        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
        }
    }

    @Override
    public void onLoadMoreRequested() {
        page = page + 1;
        GetTAGoods();
    }

    private void initUI() {
        frament_head = inflater.inflate(R.layout.osthematic_head_banner, null, false);
        osthematic_head_banner_iv = (ImageView) frament_head.findViewById(R.id.osthematic_head_banner_iv);
        adapter = new Adapt(mcontext, listdata, "");
        adapter.setLoadMoreView(new CustomLoadMoreView());
        adapter.setOnLoadMoreListener(this, listview);
        adapter.addHeaderView(frament_head);
        listview.setLayoutManager(mLayoutManager);
        // ta_ryview.GetToTop((ImageView) view.findViewById(R.id.top), 0);

        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter1, View view, int position) {
                ObjectUtils.ToDetailActivity(mcontext, 1, listdata.get(position).getId(), "");
            }
        });
    }

    private class GroupFragmentPagerAdapter extends FragmentPagerAdapter {

        public GroupFragmentPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return Fragment_TA_TabList.newInstance(ta_id, cat_list.get(position).getId(), position);
        }

        @Override
        public int getCount() {
            return cat_list.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return cat_list.get(position).getCatname();
        }
    }

    private void GetTAGoods() {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            String address = ConstantsUrl.domain + ConstantsUrl.THEMATICGOODSLIST;
            HashMap<String, String> map = new HashMap<>();
            map.put("id", ta_id);
            map.put("page", page + "");
            HttpUtils.get(address, map, new ThematicAGoodsDataCallback() {

                @Override
                public void onError(Call call, Exception e, int id) {
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                }

                @Override
                public void onResponse(ThematicAGoodsData response, int id) {
                    if (response == null) {
                        ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
                        return;
                    }
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
                    if (response.getCode() == 0) {
                        ThematicAGoodsData.DataBean data = response.getData();
                        if (data != null) {
                            List<ThematicAGoodsData.DataBean.ListDataBean> list = data.getList();
                            List<ThematicAGoodsData.DataBean.Cat_listDataBean> catList = data.getCat_list();
                            if (ObjectUtils.listHasData(catList)) {
                                cat_list.add(new ThematicAGoodsData.DataBean.Cat_listDataBean("0", "全部"));
                                cat_list.addAll(catList);
                                pagerAdapter = new GroupFragmentPagerAdapter(mcontext.getSupportFragmentManager());
                                viewPager.setAdapter(pagerAdapter);
                                tabLayout.setupWithViewPager(viewPager);
                                single_talist_fragment.setVisibility(View.GONE);
                                twocascade_talist_fragment.setVisibility(View.VISIBLE);
                            } else {
                                listdata = new ArrayList<>();
                                ThematicAGoodsData.DataBean.TopicDateBean topic = data.getTopic();
                                if(topic!=null && ObjectUtils.listHasData(topic.getThumbs())){
                                    List<String> thumbs = topic.getThumbs();
                                    ObjectUtils.photo(mcontext, thumbs.get(0), osthematic_head_banner_iv);
                                }else {
                                    adapter.removeHeaderView(frament_head);
                                }
                                if (ObjectUtils.listHasData(list)) {
                                    listdata.addAll(list);
                                    if (page == 1) {
                                        adapter.setNewData(listdata);
                                        listview.setAdapter(adapter);
                                    } else {
                                        adapter.addData(listdata);
                                        adapter.loadMoreComplete();
                                    }
                                } else {
                                    adapter.loadMoreEnd();
                                }
                            }
                        } else {
                            if (page == 1) {
                                noData.setVisibility(View.VISIBLE);
                            } else {
                                adapter.loadMoreEnd();
                            }
                            return;
                        }
                    } else {
                        if (page == 1) {
                            noData.setVisibility(View.VISIBLE);
                        } else {
                            adapter.loadMoreFail();
                            ObjectUtils.toast(mcontext, response.getMsg());
                        }
                    }
                }
            });
        } else {
            if (page == 1) {
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
            }
            ObjectUtils.toast(mcontext, "网络未连接");
        }
    }

    public class Adapt extends BaseMultiItemQuickAdapter<ThematicAGoodsData.DataBean.ListDataBean, BaseViewHolder> {
        private LayoutInflater Inflater;
        private Context content;

        public Adapt(Context content, List<ThematicAGoodsData.DataBean.ListDataBean> data, String type) {
            super(data);
            addItemType(ConstantsUrl.THEMATICGOODSLISTItemTYPE, R.layout.item_grid_detail_like);
            this.content = content;
            this.Inflater = LayoutInflater.from(content);
        }

        @Override
        protected void convert(BaseViewHolder holder, ThematicAGoodsData.DataBean.ListDataBean mainlistdata) {
            switch (holder.getItemViewType()) {
                case ConstantsUrl.THEMATICGOODSLISTItemTYPE:
                    ((TextView) holder.getView(R.id.item_grid_detail_like_number_before)).getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                    ObjectUtils.photo2(content, mainlistdata.getImg_src(), (ImageView) holder.getView(R.id.item_grid_detail_like_img));
                    holder.setText(R.id.item_grid_detail_like_title, mainlistdata.getName());
                    holder.setText(R.id.item_grid_detail_like_number_after, mainlistdata.getTeam_price());
                    holder.setText(R.id.item_grid_detail_like_number_before, mainlistdata.getPrice());
//                    holder.setText(R.id.item_grid_detail_like_tuanshu, "已团" + mainlistdata.getSell() + "件");
                    String sellNum = mainlistdata.getSell_num();
                    if (!TextUtils.isEmpty(sellNum) && !sellNum.equals("0")) {
                        holder.setText(R.id.item_grid_detail_like_tuanshu, "已团" + sellNum + "件");
                    }
                    break;
            }
        }
    }
}
